import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { useUserStore } from './userStore'
import { insertCartAPI, findNewCartListAPI, delCartAPI } from '@/apis/cart'

export const useCartStore = defineStore(
  'cart',
  () => {
    const userStore = useUserStore()
    const isLogin = computed(() => userStore.userInfo.token)
    const cartList = ref([])

    const updateNewList = async () => {
      const res = await findNewCartListAPI()
      cartList.value = res.result
    }
    const addCart = async (goods) => {
      if (isLogin.value) {
        await insertCartAPI({ skuId: goods.skuId, count: goods.count })
        updateNewList()
      } else {
        const item = cartList.value.find((item) => goods.skuId == item.skuId)
        if (item) {
          item.count++
        } else {
          cartList.value.push(goods)
        }
      }
    }
    const delCart = async (skuId) => {
      if (isLogin.value) {
        await delCartAPI([skuId])
        updateNewList()
      } else {
        const idx = cartList.value.findIndex((item) => {
          item.skuId === skuId
        })
        cartList.value.splice(idx - 1, 1)
      }
    }
    const clearCart = () => {
      cartList.value = []
    }
    const singleCheck = (skuId, selected) => {
      const item = cartList.value.find((item) => item.skuId === skuId)
      item.selected = selected
    }
    const allCheck = (selected) => {
      cartList.value.forEach((item) => (item.selected = selected))
    }
    const allCount = computed(() =>
      cartList.value.reduce((count, item) => (count += item.count), 0),
    )
    const allPrice = computed(() =>
      cartList.value.reduce((count, item) => (count += item.price * item.count), 0),
    )
    const isAll = computed(() => cartList.value.every((item) => item.selected))

    const selectedCount = computed(() => {
      return cartList.value
        .filter((item) => item.selected)
        .reduce((count, item) => (count += item.count), 0)
    })
    const selectedPrice = computed(() => {
      return cartList.value
        .filter((item) => item.selected)
        .reduce((count, item) => (count += item.price * item.count), 0)
    })
    return {
      cartList,
      addCart,
      delCart,
      clearCart,
      allCount,
      allPrice,
      singleCheck,
      isAll,
      allCheck,
      selectedCount,
      selectedPrice,
      updateNewList,
    }
  },
  {
    persist: true,
  },
)
